package org.jiuling.servlet.spring.aspect;

import org.jiuling.servlet.spring.annotation.GetIp;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.jiuling.servlet.tools.request.AnalysisRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * 追加IP切面
 * @author 紫灵
 * @date 2023年01月04日 22时23分06秒
 */
@Aspect
@Component
public class GetIpAspect {

    @Pointcut("@annotation(org.jiuling.servlet.spring.annotation.GetIp)")
    public void fun(){
    }

    @Around("fun()")
    public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null){
            HttpServletRequest request = servletRequestAttributes.getRequest();
            // 获取ip地址
            String ip = AnalysisRequest.getIp(request);

            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();

            // 获取方法参数
            Object[] args = joinPoint.getArgs();
            Parameter[] parameters = method.getParameters();

            for (int i = 0; i < parameters.length; i++) {
                Parameter parameter = parameters[i];
                // 如果参数名称为IP或者包含了GetIp注解，则替换为IP地址
                if ("ip".equals(parameter.getName()) || parameter.isAnnotationPresent(GetIp.class)){
                    args[i] = ip;
                    return joinPoint.proceed(args);
                }
            }
        }
        return joinPoint.proceed();
    }

}